import { AIToken } from "@/utils/cache";

type Options = {
  url: string;
  header?: {
    Authorization?: string;
    "Content-Type"?: string;
    token?: string;
  };
  method?: UniApp.RequestOptions["method"];
  params?: string | AnyObject | ArrayBuffer;
  data?: string | AnyObject | ArrayBuffer;
};

// #ifdef H5
const BASE_URL =
  import.meta.env.MODE !== "development" ? "https://robot.lnkyeah.com" : "";
// #endif

// #ifdef MP-WEIXIN
const BASE_URL = "https://robot.lnkyeah.com";
// #endif

async function request(options: Options) {
  const { url, method = "POST", header = {}, data = {}, ...rest } = options;
  return await uni.request({
    url: `${BASE_URL}${url}`,
    header,
    data,
    ...rest
  });
}

export async function socketLogin() {
  const res = await request({
    url: "/index/socket_login",
    header: {
      Authorization: AIToken.get()
    }
  });

  if (res.data.code === 200) {
    return [null, res.data];
  } else if (res.data.code === 401) {
    uni.showModal({
      title: "提示",
      content: "登录已失效，请重新登录",
      confirmText: "去登录",
      success(res) {
        if (res.confirm) {
          uni.navigateTo({
            url: "/pages/login/login"
          });
        }
      }
    });
  }
  return [res, null];
}

export async function socketSpeekLogin() {
  const res = await request({
    url: "/index/speek",
    header: {
      Authorization: AIToken.get()
    }
  });
  if (res.data.code === 200) {
    return [null, res];
  }
  return [res, null];
}

export async function socketTTS(messages: string, voice_id = "29") {
  const formData = new FormData();
  formData.append("messages", messages);
  formData.append("voice_id", voice_id);
  const response = await fetch(BASE_URL + "/tts/add", {
    method: "POST",
    headers: {
      Authorization: AIToken.get()
    },
    body: formData
  });
  const res = await response.text();
  if (res) {
    return [null, res];
  }
  return [res, null];
}
